package com.mxpio.erp.plan.job;

import com.mxpio.erp.common.enums.OrderStatusEnums;
import com.mxpio.erp.common.enums.PlanEnums;
import com.mxpio.erp.common.plan.entity.MpsVersion;
import com.mxpioframework.jpa.JpaUtil;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.mxpio.erp.plan.mrp.Context;
import com.mxpio.erp.plan.mrp.service.LrpCoreService;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Component
public class LrpJob implements Job {
	
	private static final Logger log = LoggerFactory.getLogger(LrpJob.class);

	@Autowired
	private LrpCoreService lrpCoreService;
	
	@Override
	@Transactional
	public void execute(JobExecutionContext context) throws JobExecutionException {
		
		try {
			log.info("MRP:===========Job start============");
			List<MpsVersion> effectiveMpsVersions = JpaUtil.linq(MpsVersion.class)
					.equal("bpmnStatus", OrderStatusEnums.BpmnStatus.AUDITED.getStatusCode())
					.equal("effectiveStatus", PlanEnums.EffectiveStatus.YES.getCode())
					.list();
			if (effectiveMpsVersions.size()==0){
				log.error("系统中未存在生效中的主计划版本，请先维护数据！");
				return;
			}
			lrpCoreService.clearAdvice();
			Context lrpContext = Context.defaultContext();
			lrpCoreService.initContext(lrpContext);
			lrpCoreService.runLrp();
			log.info("MRP:===========Job end============");
		} catch (Exception e) {
			log.error("MRP:===========Job Exception============");
			log.error(e.getMessage());
			log.error(e.getStackTrace().toString());
			e.printStackTrace();
		}
	}

}
